package com.ocl.www.controller;

import com.ocl.www.domain.Article;
import com.ocl.www.domain.MyCollection;
import com.ocl.www.domain.UserFavorite;
import com.ocl.www.service.ArticleService;
import com.ocl.www.service.MyCollectionService;
import com.ocl.www.service.UserFansService;
import com.ocl.www.service.UserFavoriteService;
import com.ocl.www.utils.UserUntil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.el.parser.ArithmeticNode;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.ocl.www.basic.BasicController;

import java.sql.Timestamp;
import java.util.*;

@RestController
@RequestMapping("/userFavorite")
public class UserFavoriteController  extends BasicController {

    @Autowired
    private UserFavoriteService userFavoriteService;
    @Autowired
    private MyCollectionService myCollectionService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private EhCacheManager cacheManager;

    private Logger log = Logger.getLogger(UserFavoriteController.class);

    /**
     * 判断是否点赞及是否收藏
     * @param maptemp
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/isFavoriteAndCollection",method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="判断是否点赞及是否收藏", notes="判断是否点赞及是否收藏(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> isFavoriteAndCollection(@RequestBody Map<String,Object> maptemp){

        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setArticleId(Integer.valueOf(maptemp.get("articleId").toString()));
        try{
            userFavorite.setUserId(UserUntil.getUserId(SecurityUtils.getSubject().getPrincipals().asSet()));
        }catch (NullPointerException e){
            log.info(e.getMessage());
        }


        MyCollection myCollection = new MyCollection();
        myCollection.setArticleId((String) maptemp.get("articleId"));
        try{
            myCollection.setUserId(String.valueOf(UserUntil.getUserId(SecurityUtils.getSubject().getPrincipals().asSet())));
        }catch (NullPointerException e){
            log.info(e.getMessage());
        }

        try {
            maptemp.put("userFavoriteslist",userFavoriteService.selectFavorites(userFavorite).size());
            maptemp.put("myCollectionlist",myCollectionService.selectMyCollections(myCollection).size());
            maptemp.put("info","s");
            return maptemp;
        } catch (Exception e) {
            //e.printStackTrace();
            maptemp.put("info","e");
            maptemp.put("error",e.getMessage());
            return maptemp;
        }

    }
    /**
     * 点赞
     * @param maptemp
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/insertFavorite",method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="点赞", notes="点赞(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> insertFavorite(@RequestBody Map<String,Object> maptemp){

        try {
            log.info("secu : "+ SecurityUtils.getSubject().getPrincipals().asList());
            maptemp.put("islogin",1);
        }catch (NullPointerException e){
            maptemp.put("info","s");
            maptemp.put("tip","no user login");
            maptemp.put("islogin",0);
            return maptemp;
        }


        Set<?> s = SecurityUtils.getSubject().getPrincipals().asSet();
        Object[] obj = new Object[2];
        int obji = 0;
        Iterator<?> it = s.iterator();
        while(it.hasNext()){
            obj[obji] = it.next();
            log.info(obj.getClass());
            log.info(obj.toString());
            obji++;
        }
        Map<String,String> map = (Map<String, String>) obj[1];

        String userId = map.get("userId").toString();


        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setUserId(Integer.valueOf(userId));
        userFavorite.setArticleId(Integer.valueOf(maptemp.get("articleId").toString()));

        try {
            int count = 0;
            List<UserFavorite> clist = userFavoriteService.selectFavoritesCount(userFavorite);
            count = clist.size();
            if (count >= 1){
                maptemp.put("info","f");
                maptemp.put("tip","不可重复点赞！");
                return maptemp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        Date d = new Date();
        userFavorite.setCreateTime(new Timestamp(d.getTime()));
        int c = 0 ;
        int c1 = 0;
        try {
            c = userFavoriteService.insertFavorite(userFavorite);
            if(c==1){
                Article art = new Article();
                art.setArticleId(Integer.valueOf(maptemp.get("articleId").toString()));
                c1 = articleService.addOneLikeCount(art);
            }
        } catch (Exception e) {
            e.printStackTrace();
            c = 0;
        }
        maptemp.put("c",c);
        maptemp.put("c1",c1);
        return maptemp;
    }



    @ResponseBody
    @RequestMapping(value="/deleteFavorite",method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="减赞", notes="减赞(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> deleteFavorite(@RequestBody Map<String,Object> maptemp){

        log.info("secu : "+ SecurityUtils.getSubject().getPrincipals().asList());
        Set<?> s = SecurityUtils.getSubject().getPrincipals().asSet();
        Object[] obj = new Object[2];
        int obji = 0;
        Iterator<?> it = s.iterator();
        while(it.hasNext()){
            obj[obji] = it.next();
            log.info(obj.getClass());
            log.info(obj.toString());
            obji++;
        }
        Map<String,String> map = (Map<String, String>) obj[1];

        String userId = map.get("userId").toString();


        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setFavoriteId(Integer.valueOf(maptemp.get("favoriteId").toString()));
//        userFavorite.setUserId(Integer.valueOf(userId));
//        userFavorite.setArticleId(Integer.valueOf(maptemp.get("articleId").toString()));
//        Date d = new Date();
//        userFavorite.setCreateTime(new Timestamp(d.getTime()));

        int c = 0 ;
        try {
            c = userFavoriteService.deleteFavorite(userFavorite);

        } catch (Exception e) {
            e.printStackTrace();
            c = 0;
        }
        maptemp.put("c",c);
        return maptemp;
    }

    @ResponseBody
    @RequestMapping(value = "/selectFavorites",method = RequestMethod.POST ,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value="查询文章的点赞数", notes="查询文章的点赞数(post方式)")
    @ApiImplicitParam(name = "maptemp", value = "使用此格式：{}", required = true, dataType = "Map")
    public Map<String,Object> selectFavorites(@RequestBody Map<String,Object> maptemp){

        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setArticleId(Integer.valueOf(maptemp.get("articleId").toString()));
        List<UserFavorite> userFavoriteList = new ArrayList<UserFavorite>();
        try {
            userFavoriteList = userFavoriteService.selectFavorites(userFavorite);
            maptemp.put("userFavoriteList",userFavoriteList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return maptemp;

    }
}
